/* Copyright (C) 2010 Fredrique Samuels, fredriquesamuels@gmail.com 

 This program is free software: you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation, either version 3 of the License, or
 (at your option) any later version.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

#include "timer.h"


#include <assert.h>

namespace tri {

TProgressTimer::TProgressTimer(){
    
    m_StartTime = -1;
    m_EndTime = -1;
    m_Duration = 1.0;
    m_Mode = CLOCK_TYPE;
}

TProgressTimer::~TProgressTimer() {
    stop();
}


void TProgressTimer::reset() {
    stop();
    start();
}

bool TProgressTimer::start() {
    
    if (isRunning()){
        return false;
    }
    
    switch(m_Mode){
    case CLOCK_TYPE:
        m_StartTime = clock();
        m_EndTime = -1;
        break;
    case TIMER_TYPE:
        m_StartTime = clock();
        m_EndTime = m_StartTime + (int)( (float)m_Duration *(float)CLOCKS_PER_SEC );
        break;
    }
    
    return true;
}

void TProgressTimer::stop(){
    m_StartTime = m_EndTime = 0;
}

double TProgressTimer::getProgress() {
    if (isRunning() && m_Mode == TIMER_TYPE){
        double t = getElapsedTime();
        return t/m_Duration;
    }
    
    return 1.0;
}

double TProgressTimer::getElapsedTime(){
    
    if(isRunning()){
        switch(m_Mode){
        case CLOCK_TYPE:
            return (double)( clock()-m_StartTime ) / (double)CLOCKS_PER_SEC;
        case TIMER_TYPE:
            double elapsed = (double)( clock()-m_StartTime ) / (double)CLOCKS_PER_SEC;
            if( elapsed > m_Duration){
                m_StartTime = m_EndTime;
                return m_Duration;
            }
            return elapsed;
        }
    }
    return 0;
}

bool TProgressTimer::isRunning() {
    return !( m_StartTime == m_EndTime );
}

void TProgressTimer::setDurationTime(double t) {
    if (isRunning()){
        return;
    }
    if (t < 0) {
        t = 0;
    }
    m_Duration = t;
    m_StartTime = m_EndTime = 0;
    
}

void TProgressTimer::setMode(ProgressTimerSetting m){
    assert(  ( m == CLOCK_TYPE || m==TIMER_TYPE )  );
    m_Mode =m;
}

ProgressTimerSetting TProgressTimer::getMode(){
    return m_Mode;
}

}
